<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { sensorByIdDvalue, sensorByIdDiff } from "@T2/service/api.ts";
import * as echarts from 'echarts';
import vueECharts from "vue-echarts";
import dayjs from 'dayjs';

const props = defineProps({
  params: {
    type: Array,
    required: true,
  },
  updateFlag: {
    type: Boolean,
    default: false,
  }
});
const chartRef = ref(null);
onMounted(() => {
  beforeGetData();
});
const Resd = reactive({
  unit: '',
});
const colors = {
  day: [
    new echarts.graphic.LinearGradient(0,0,1,0, [{offset: 0, color: '#1B91FF'}, {offset: 1, color: '#695AFF'}]),
    new echarts.graphic.LinearGradient(0,0,1,0, [{offset: 0, color: '#FFE583'}, {offset: 1, color: '#FCBD33'}]),
  ]
}
const option = {
  animation: true,										  	  //默认，是否开启动画
  backgroundColor: 'rgba(0, 18, 24, 0)',    //默认，无背景颜色
  color: ['#02F7A1', '#0EB7FF'],
  dataset: [],                              //默认，数据集
  series: [],                               //默认，系列
  tooltip: {
    trigger: 'axis',                        //默认，axis坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。
    backgroundColor: 'rgba(0,28,32,0.96)',  //提示框背景颜色
    borderColor: 'rgba(23,178,178,0.6)',    //提示框边框颜色
    textStyle: {
      color: '#D3F2EE',                     //提示框字体颜色
      fontSize: 14,                         //提示框字体大小
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 500,
    },
  },
  legend: {
    icon: 'rect',                        //默认，图例icon
    top: 0,                              //图例距容器顶部距离
    itemWidth: 9,                        //图例图形宽度
    itemHeight: 9,                       //图例图形高度
    textStyle: {
    	color: '#B2B2B2',                  //图例文字颜色
    	fontSize: 12,                      //图例文字大小
    },
  },
  grid: {
    // containLabel: true,                   //默认，为true表示外边 距离 包含刻度标签在内的整个图表
    bottom: 25,                           //默认，网格离容器底部距离
    right: '2.5%',                        //默认，网格离容器右侧距离
    left: 40,                             //默认，网格离容器左侧距离
    top: 32,                              //网格离容器顶部距离
  },
  xAxis: {
    boundaryGap: false,                   //默认， boundaryGap值为false的时候，折线第一个点在y轴上
    type: 'time',                         //默认，时间轴
    axisLine: {
      lineStyle: {
        width: 1,
        color: '#FFFFFF',
        type: [5, 3],
        opacity: 0.5,
      }
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: '#FFFFFF',
      fontSize: 12,
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      width: 30,
      interval:0,
      overflow: 'break',
    },
  },
  yAxis: {
    type: 'value',                        //默认，数值轴
    splitLine: {
      lineStyle: {
        color: '#A9A9A9',
        type: [5, 3],
      }
    },
    axisLabel: {
      color: '#FFFFFF',
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      lineHeight: 14,
      fontSize: 12,                       //刻度标签字体大小
      align: 'left',
      margin: 40,
      padding: 0,
      // inside: true,
    },
    nameTextStyle: {
      color: "#FFFFFF",                   //坐标轴名称字体颜色
      fontSize: 12,                       //坐标轴名称字体大小
      lineHeight: 21,
    },
  },
}
let yMax = 0, unitCg = 'first', seriesInfo = [];
watch(() => props.updateFlag, (nv, ov) => {
  if (nv) {
    beforeGetData();
  }
});
function beforeGetData() {
  // chartRef.value.chart.clear();
  option.dataset = [];
  option.series = [];
  option.legend.data = [];
  yMax = 0;
  unitCg = 'first';
  seriesInfo = [];
  props.params.forEach((params, index) => {
    if (params.t === "ch") {
      getHourLine(params, index);
    } else if (params.t === "cd") {
      getDayLine(params, index);
    } else if (params.t === "cm") {
      getMonthBar(params, index);
    }
  });
}
function getHourLine(params, pInd) {
  params.s && sensorByIdDvalue({
  	method: "get",
  	id: params.s,
  	params: {
  		status: "每小时",
  		start: dayjs().format('YYYY-MM-DD') + " 01:00:00",
  		end: dayjs(dayjs().format('YYYY-MM-DD')).add(1, 'day').format("YYYY-MM-DD") + " 00:01:00",
  	},
  }).then(res => {
    let { results, unit, } = res;
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'hour').format("YYYY-MM-DD HH") + ":00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    dValueCommon(source, unit, params, pInd, 'dayLine');
    option.xAxis.min = dayjs().format('YYYY-MM-DD') + " 00:00:00";
    option.xAxis.max = dayjs().format('YYYY-MM-DD') + " 23:59:59";
    option.xAxis.splitNumber = 4;
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('HH时');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("YYYY-MM-DD HH时");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
        let color = ser.seriesName === '出水' ? '#FCBD33' : '#1B91FF';
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              // + ser.marker
              + `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getDayLine(params, pInd) {
  Promise.all([getDayDvalue(params), getIdDiff(params)]).then(res => {
    let { results, unit, } = res[0];
    let { today } = res[1];
    if (dayjs().format('YYYY-MM') === dayjs().format('YYYY-MM')) {
      results.push({
        id: null,
        create_time: dayjs().add(1, 'day').format("YYYY-MM-DD") + " 00:01:00",
        data: today,
      });
    }
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'day').format("YYYY-MM-DD") + " 00:00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    dValueCommon(source, unit, params, pInd, 'monthLine');
    option.xAxis.min = dayjs().format('YYYY-MM') + "-01 00:00:00";
    option.xAxis.max = dayjs(dayjs().format('YYYY-MM')).add(1, 'month').subtract(1, 'day').format("YYYY-MM-DD") + " 01:00:00";
    option.xAxis.splitNumber = 5;
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('DD日');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("DD日");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
        let color = ser.seriesName === '出水' ? '#0EB7FF' : '#02F7A1';
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              // + ser.marker
              + `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getDayDvalue(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDvalue({
			method: "get",
			id: params.s,
			params: {
				status: "每日",
				start: dayjs().format("YYYY-MM") + "-02 00:00:00",
				end: dayjs(dayjs().format('YYYY-MM')).add(1, 'month').format("YYYY-MM") + "-01 00:01:00",
			},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getMonthBar(params, pInd) {
  Promise.all([getMonthDvalue(params), getIdDiff(params)]).then(res => {
    let { results, unit, } = res[0];
    let { month } = res[1];
    if (dayjs().format('YYYY') === dayjs().format('YYYY')) {
      results.push({
        id: null,
        create_time: dayjs().add(1, 'month').format("YYYY-MM") + "-01 00:01:00",
        data: month,
      });
    }
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'month').format("YYYY-MM") + "-01 00:00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    dValueCommon(source, unit, params, pInd, 'bar');
    option.xAxis.min = dayjs().format('YYYY') + "-01-01 00:00:00";
    option.xAxis.max = dayjs(dayjs().format('YYYY')).add(1, 'year').subtract(1, 'month').format("YYYY-MM") + "-02 00:00:00";
    option.xAxis.splitNumber = 5;
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('MM月');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("MM月");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
        let color = ser.seriesName === '出水' ? '#0EB7FF' : '#02F7A1';
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              // + ser.marker
              + `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getMonthDvalue(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDvalue({
			method: "get",
			id: params.s,
			params: {
				status: "每月",
				start: dayjs().format("YYYY") + "-02-01 00:00:00",
				end: dayjs(dayjs().format('YYYY')).add(1, 'year').format("YYYY") + "-02-01 00:01:00",
			},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getIdDiff(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDiff({
			method: "get",
			id: params.s,
			params: {},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getMulPower(len = 1, max = 0) {
  if (len === 0) {
    return 1;
  } else {
    const consult = max / (len - 1) / 2;
    const exp = consult.toExponential().split('e');
    const x = +exp[0];
    const y = +exp[1];
    return +(x * 10 ** y).toFixed(1);
  }
}

function dValueCommon(source, unit, params, pInd, type = 'line') {
  option.dataset.push({
    dimensions: ['time', 'data', 'miniData'],
    source,
  });
  seriesInfo.push({
    unit: unit,
    oriUnit: unit,
  });
  const len = option.dataset.length - 1;
  if (type === 'dayLine') {
    let flag = pInd ? 1 : 0;
    const sColor = colors.day[flag];
    const lColor = colors.day[flag];
    option.series.push({
    	name: params.n,
      datasetIndex: len,
    	type: "line",
    	showSymbol: true,       //不加这个会导致多系列时，只有一个系列显示了标记
    	symbolSize: 4,
      symbol: 'circle',
      itemStyle: {
        color: sColor,
      },
    	lineStyle: {
        color: sColor,
    		width: 1,
    	},
    });
    option.legend.data.push({
      name: params.n,
      itemStyle: {
        color: lColor,
      },
    });
  } else if (type === 'monthLine') {
    let flag = pInd ? 1 : 0;
    const sColor = ['#02F7A1', '#0EB7FF'][flag];
    const lColor = ['#02F7A1', '#0EB7FF'][flag];
    const areaColor = ['rgba(2,247,161,0.3)', 'rgba(14,183,255,0.3)'][flag];
    option.series.push({
    	name: params.n,
      datasetIndex: len,
    	type: "line",
    	showSymbol: true,       //不加这个会导致多系列时，只有一个系列显示了标记
    	symbolSize: 0,
    	lineStyle: {
        color: sColor,
    		width: 1,
    	},
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0,1,0,0, [{offset: 0, color: 'rgba(159,255,221,0)'}, {offset: 1, color: areaColor}]),
      },
    });
    option.legend.data.push({
      name: params.n,
      itemStyle: {
        color: lColor,
      }
    });
  } else if (type === 'bar'){
    let flag = pInd ? 1 : 0;
    const sColor = [
      new echarts.graphic.LinearGradient(0,1,0,0, [{offset: 0, color: '#10292D'}, {offset: 0.95, color: '#00623e'}, {offset: 1, color: '#02F7A1'}]),
      new echarts.graphic.LinearGradient(0,1,0,0, [{offset: 0, color: '#10292D'}, {offset: 1, color: '#0EB7FF'}]),
    ][flag];
    const lColor = ['#02F7A1', '#0EB7FF'][flag];
    option.series.push({
    	name: params.n,
      datasetIndex: len,
    	type: "bar",
    	barWidth: 10,
      barGap: '-100%',
    	itemStyle: {
        color: sColor,
    	  borderRadius: 6,
        shadowColor: '#000000'
    	},
      z: flag ? 3 : 2,
    });
    option.legend.data.push({
      name: params.n,
      itemStyle: {
        color: lColor,
      }
    });
  }
  encodeCheck(unit, params);
}

function encodeCheck(unit, params) {
  if (unitCg === 'first' || unitCg === unit) {
    if (unitCg === 'first') {
      unitCg = unit;
    }
    if (yMax > 10000) {
      // option.yAxis.name = '万' + unit;
      // option.yAxis.name = '单位：' + option.yAxis.name;
      Resd.unit = '单位：' + '万' + unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'miniData' }
        }
      });
      seriesInfo.forEach(i => {
        if (!i.step) {
          i.unit = '万' + i.oriUnit;
        }
      });
    } else {
      // option.yAxis.name = unit;
      // option.yAxis.name = '单位：' + option.yAxis.name;
      Resd.unit = '单位：' + unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'data' }
        }
      });
    }
  } else {
    unitCg = 'error';
    // option.yAxis.name = '';
    Resd.unit = '';
    option.series.forEach(i => {
      if (!i.step) {
        i.encode = { x: 'time', y: 'data' }
      }
    });
  }
}


</script>

<template>
  <div class="u_c_box">
    <div class="v_charts_box">
      <vueECharts ref="chartRef" autoresize :option="option" />
    </div>
    <span>{{ Resd.unit }}</span>
  </div>
</template>

<style lang="scss" scoped>
.u_c_box {
  width: 100%;
  height: 250px;
  position: relative;
  .v_charts_box {
    width: 100%;
    height: 100%;
  }
  >span {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 12px;
    color: #FFFFFF;
    line-height: 14px;
  }
}
</style>